﻿using System;
using System.Collections;
using System.DirectoryServices;
using System.IO;
using System.Text;

namespace Axiom.CodeManifold.Tools.ActiveDirectory
{
	public class ADComponent
	{
		public IList RunQuery(string query)
		{
			var sb = new StringBuilder();

			IList rval = new ArrayList();
			SearchResultCollection searchResults = null;
			DirectorySearcher srch = new DirectorySearcher("");
			srch.Filter = query;
			try
			{
				searchResults = srch.FindAll();

				foreach (SearchResult result in searchResults)
				{
					//if (result.Properties["distinguishedName"].Count == 0) continue;
					DirectoryEntry entry = new DirectoryEntry("LDAP://" + result.Properties["distinguishedName"][0]);
					ResultPropertyCollection properties = result.Properties;

					if (result.Properties != null && result.Properties["userprincipalname"] != null && result.Properties["userprincipalname"][0] != null)
					{
						sb.AppendLine(result.Properties["userprincipalname"][0].ToString());
					}

					//foreach (DictionaryEntry item in properties)
					//{
					//    var collection = item.Value as System.DirectoryServices.ResultPropertyValueCollection;
					//    foreach (var child in collection)
					//    {
					//        string s = string.Format("{0} - {1}", item.Key, child.ToString());
					//        sb.AppendLine(s);
					//    }
					//}

					//sb.AppendLine();
					//sb.AppendLine();
					//rval.Add(LoadUser(properties));
				}
			}
			catch (Exception ex)
			{

			}

			File.WriteAllText("email-data.txt", sb.ToString());
			return rval;
		}
	}
}
